using Microsoft.Extensions.Options;
using SKIT.FlurlHttpClient.Wechat.TenpayV3;
using SKIT.FlurlHttpClient.Wechat.TenpayV3.Settings;
using SKIT.FlurlHttpClient.Wechat.TenpayV3.Utilities;
using Vin.Extension.Framework.Base;
using Vin.Extension.Framework.Wechat.Pay.Options;
using Vin.Tool.AspNetCore.Options;
using Vin.Tool.AspNetCore.Singleton;
using Vin.Tool.Attributes;
using Vin.Tool.Core.AssertCategory;
using Vin.Tool.Core.BasicTypeCategory;

namespace Vin.Extension.Framework.Wechat.Pay.Service;

public class VinWxPayV3BaseService : VinFrameworkBaseService
{
    private static InMemoryCertificateManager _certificateManager = new InMemoryCertificateManager();

    protected VinOption VinOption => VinApp.GetConfig<VinOption>();
    protected WechatPayOption WechatPayOption => VinApp.GetConfig<WechatPayOption>();

    protected string SiteUrl => VinOption.SiteUrl.IsNullOrWhiteSpace()
        ? throw new System.Exception("请配置Vin:SiteUrl")
        : VinOption.SiteUrl!;
    
    protected string NotifyUrl => WechatPayOption.V3NotifyUrl.IsNotNullOrEmpty()
        ? WechatPayOption.V3NotifyUrl.IsUrl()
            ?  WechatPayOption.V3NotifyUrl
            : $"{SiteUrl}{ WechatPayOption.V3NotifyUrl}"
        : string.Empty;
    
    public WechatTenpayClient? WxPayClient => WechatPayOption.AppId.IsNullOrEmpty()
        ? null
        : WechatTenpayClientBuilder.Create(new WechatTenpayClientOptions()
        {
            MerchantId = WechatPayOption.MerchantId,
            MerchantV3Secret = WechatPayOption.MerchantV3Secret,
            MerchantCertificateSerialNumber =
                RSAUtility.ExportSerialNumberFromCertificate(File.ReadAllText(WechatPayOption.CertPemPath)),
            MerchantCertificatePrivateKey = File.ReadAllText(WechatPayOption.KeyPemPath),
            PlatformCertificateManager = _certificateManager,
        }).Build();
}